package com.booklove.config;


import com.booklove.interceptor.JwtTokenUserInterceptor;
import com.booklove.json.JacksonObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;


import java.util.List;

/**
 * 配置类，注册web层相关组件
 */
@Configuration
@Slf4j
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

    @Autowired
    private JwtTokenUserInterceptor jwtTokenUserInterceptor;

    /**
     * 注册自定义拦截器
     *
     * @param registry
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        log.info("开始注册自定义拦截器...");

        registry.addInterceptor(jwtTokenUserInterceptor)
                .addPathPatterns("/user")
                .excludePathPatterns("/user/user/login")
                .excludePathPatterns("/user/user/register")
                .excludePathPatterns("/user/user/wxlogin")
                .addPathPatterns("/test/**")
                .excludePathPatterns("/test/login")
                .addPathPatterns("/book/**")
                .addPathPatterns("/wishbooks/**")
                .addPathPatterns("/donatebooks/**")
                .addPathPatterns("/book/**")
                .addPathPatterns("/deliver/**")
                .addPathPatterns("voluntarywork/**")
                .addPathPatterns("/address/**")
                .addPathPatterns("/notesjudge/**")
                .addPathPatterns("/notes/**")
                .addPathPatterns("/orders/**");
    }


    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        log.info("注册新的jsons数据转换器");
        // 更换新的序列化器件
//        MappingJackson2CborHttpMessageConverter : 注意不要使用这个
        //创建消息转换器对象
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        //需要创建一个新的消息转换器
        converter.setObjectMapper(new JacksonObjectMapper());
        //将船创建好的消息转换器对象加入
        converters.add(0, converter);
    }

    /**
     * 设置静态资源映射
     * @param registry
     * 如果对MVC层进行了修改，需要主动对静态资源进行映射设置
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        log.info("静态资源导入");
        // 静态路径的方式进行对handler的放行 和 swagger文档的注入
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}



